package com.jp.knowledge.activity;

import android.content.Intent;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;

import com.canyinghao.canrefresh.CanRefreshLayout;
import com.google.gson.JsonObject;
import com.jiayen.cache.FileCacheManager;
import com.jiayen.util.ToasUtil;
import com.jp.knowledge.R;
import com.jp.knowledge.adapter.attention.AttentionGroupDetailAdapter;
import com.jp.knowledge.comm.SlidingActivity;
import com.jp.knowledge.dialog.CommDialog;
import com.jp.knowledge.http.HttpHelper;
import com.jp.knowledge.model.IModel;
import com.jp.knowledge.model.attention.AttentionGroupDetailModel;
import com.jp.knowledge.model.attention.CompanyListModel;
import com.jp.knowledge.util.ResultSubscriber;
import com.jp.knowledge.view.JpDiver;
import com.jp.knowledge.view.SwipeItemLayout;

import java.util.ArrayList;
import java.util.List;

import rx.Observable;
import rx.Observer;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by 528787067@qq.com on 2017/3/17.
 */

public class AttentionGroupDetail extends SlidingActivity implements View.OnClickListener, ResultSubscriber.OnResultListener, CanRefreshLayout.OnRefreshListener {

    private static final int ATTENTION_GROUP_LIST_CODE = 0x01;
    private static final int ATTENTION_GROUP_CREATE = 0x02;
    private static final int ATTENTION_GROUP_DELETE = 0x03;
    private static final int ATTENTION_GROUP_RENAME = 0x04;

    private CompanyListModel.ListBean companyModel;
    private CanRefreshLayout refreshLayout;
    private RecyclerView groupDetailRv;
    private CommDialog createGroupDialog;
    private CommDialog renameGroupDialog;

    private AttentionGroupDetailAdapter adapter;
    private List<AttentionGroupDetailModel> groupDatas;

    private String cachePath;
    private FileCacheManager cacheManager;

    @Override
    protected int getResourceId() {
        return R.layout.activity_attention_group_detail;
    }

    @Override
    protected void init() {
        groupDatas = new ArrayList<>();
        companyModel = (CompanyListModel.ListBean) getIntent().getSerializableExtra("companyModel");
        refreshLayout = (CanRefreshLayout) findViewById(R.id.refresh);
        groupDetailRv = (RecyclerView) findViewById(R.id.can_content_view);
        refreshLayout.setLoadMoreEnabled(false);
        refreshLayout.setOnRefreshListener(this);
        leftIcon.setImageResource(R.mipmap.arrow_white_left);
        rightIcon.setVisibility(View.GONE);
        leftIcon.setOnClickListener(this);
        if(companyModel == null || companyModel.getTitle() == null || companyModel.getTitle().trim().length() == 0) {
            topName.setText("分组管理");
            ToasUtil.toast(this, "抱歉，分组信息有误");
            return;
        }
        topName.setText(companyModel.getTitle());
        rightBtn.setText("新建");
        rightBtn.setVisibility(View.VISIBLE);
        rightBtn.setOnClickListener(this);

        adapter = new AttentionGroupDetailAdapter(this, groupDatas);
        groupDetailRv.setHasFixedSize(true);
        groupDetailRv.setLayoutManager(new LinearLayoutManager(this));
        groupDetailRv.addItemDecoration(new JpDiver(this));
        groupDetailRv.addOnItemTouchListener(new SwipeItemLayout.OnSwipeItemTouchListener(this));
        groupDetailRv.setAdapter(adapter);
        adapter.setOnItemCallback(new AttentionGroupDetailAdapter.OnItemCallback() {
            @Override
            public void onItemClick(int position) {
                startActivity(new Intent(mContext, AttentionGroupDetailInfo.class)
                    .putExtra("id", groupDatas.get(position).getId())
                    .putExtra("title", groupDatas.get(position).getTitle())
                    .putExtra("type", 9));
                groupDatas.get(position).setNewNum(0);
                adapter.notifyItemChanged(position);
            }
            @Override
            public void onChangedClick(int position) {
                renameGroupDialog.setEditHint(groupDatas.get(position).getTitle());
                renameGroupDialog.setEditText(groupDatas.get(position).getTitle());
                renameGroupDialog.setTag(position);
                renameGroupDialog.show();
            }
            @Override
            public void onDeleteClick(int position) {
                groupDelete(groupDatas.get(position).getId(), position);
                adapter.removeData(position);
            }
        });
        createGroupDialog = new CommDialog(this);
        createGroupDialog.setEditHint("新建分组");
        createGroupDialog.setRightClickDismiss(false);
        createGroupDialog.setRightListener(this);
        createGroupDialog.setShowWithKeyword(true);

        renameGroupDialog = new CommDialog(this);
        renameGroupDialog.setRightClickDismiss(false);
        renameGroupDialog.setShowWithKeyword(true);
        renameGroupDialog.setRightListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int position = (int) renameGroupDialog.getTag();
                if(renameGroupDialog.getEditText().equals(groupDatas.get(position).getTitle())) {
                    renameGroupDialog.dismiss();
                } else if(renameGroupDialog.getEditText().trim().length() == 0){
                    ToasUtil.toast(mContext, "请输入有效的组名");
                } else{
                    for(AttentionGroupDetailModel data : groupDatas){
                        if(renameGroupDialog.getEditText().equals(data.getTitle())){
                            ToasUtil.toast(mContext, "抱歉，\"" + renameGroupDialog.getEditText() + "\"已存在");
                            return;
                        }
                    }
                    groupRename(groupDatas.get(position).getId(), renameGroupDialog.getEditText(), position);
                    groupDatas.get(position).setTitle(renameGroupDialog.getEditText());
                    adapter.notifyItemChanged(position);
                    renameGroupDialog.dismiss();
                }
            }
        });

//        refreshLayout.autoRefresh();
        initCache();
        readCache();
    }

    private void initCache(){
        cacheManager = new FileCacheManager();
        cachePath = getCacheDir().getPath() + "/attentionGroup_"
                + companyModel.getId() + "_" + companyModel.getType() + ".dat";
    }

    private void readCache(){
        Observable.create(new Observable.OnSubscribe<List<AttentionGroupDetailModel>>() {
            @Override
            public void call(Subscriber<? super List<AttentionGroupDetailModel>> subscriber) {
                List<AttentionGroupDetailModel> data = (List<AttentionGroupDetailModel>) cacheManager.readObject(cachePath);
                subscriber.onNext(data);
            }
        }).subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(new Observer<List<AttentionGroupDetailModel>>() {
            @Override
            public void onCompleted() {
                if(groupDatas.size() == 0)
                    refreshLayout.autoRefresh();
                else
                    getData(companyModel.getId(), companyModel.getType());
            }
            @Override
            public void onError(Throwable e) {
                onCompleted();
            }
            @Override
            public void onNext(List<AttentionGroupDetailModel> list) {
                groupDatas.clear();
                if(list != null && list.size() > 0)
                    groupDatas.addAll(list);
                adapter.updateAdapter(groupDatas);
                onCompleted();
            }
        });
    }

    private void saveCache(final Object data, final String path){
        new Thread(new Runnable() {
            @Override
            public void run() {
                cacheManager.wirteObject(data, path);
            }
        }).start();
    }

    @Override
    protected void onDestroy() {
        saveCache(groupDatas, cachePath);
        super.onDestroy();
    }

    @Override
    public void finish() {
        boolean hasNew = false;
        for (AttentionGroupDetailModel groupDetailModel : groupDatas){
            if(groupDetailModel.getNewNum() > 0){
                hasNew = true;
                break;
            }
        }
        setResult(RESULT_OK, getIntent().putExtra("hasNew", hasNew));
        super.finish();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.icon_left:
                finish();
                break;
            case R.id.right_bn:
                createGroupDialog.setEditText("");
                createGroupDialog.show();
                break;
            case R.id.right_btn:
                String groupName = createGroupDialog.getEditText();
                if(groupName.trim().length() == 0){
                    ToasUtil.toast(this, "请输入有效的组名");
                } else{
                    for(AttentionGroupDetailModel model : groupDatas)
                        if(groupName.equals(model.getTitle())){
                            ToasUtil.toast(this, "抱歉，\"" + groupName + "\"已存在");
                            return;
                        }
                    createGroupDialog.setTag(groupName);
                    groupCreate(companyModel.getId(), companyModel.getType(), groupName);
                    createGroupDialog.dismiss();
                }
                break;
        }
    }

    private void getData(String id, int type){
        JsonObject param = new JsonObject();
        if(id != null && !"myGroup".equals(id)) {
            param.addProperty("id", id);
            param.addProperty("type", type);
        }
        HttpHelper.getInstance(this).attentionGroupList(param, ATTENTION_GROUP_LIST_CODE, this);
    }

    private void groupCreate(String id, int type, String title){
        JsonObject param = new JsonObject();
        if(id != null && !"myGroup".equals(id)) {
            param.addProperty("id", id);
            param.addProperty("type", type);
        }
        param.addProperty("title", title);
        HttpHelper.getInstance(this).attentionGroupCreate(param, ATTENTION_GROUP_CREATE, this);
    }

    private void groupDelete(String id, int position){
        JsonObject param = new JsonObject();
        param.addProperty("id", id);
        HttpHelper.getInstance(this).attentionGroupDelete(param, position*10+ATTENTION_GROUP_DELETE, this);
    }

    private void groupRename(String id, String title, int position){
        JsonObject param = new JsonObject();
        param.addProperty("id", id);
        param.addProperty("title", title);
        HttpHelper.getInstance(this).attentionGroupRename(param, position*10+ATTENTION_GROUP_RENAME, this);
    }

    @Override
    public void onRefresh() {
        getData(companyModel.getId(), companyModel.getType());
    }

    @Override
    public void onStart(int requestType) {
        if(requestType == ATTENTION_GROUP_CREATE)
            loading.show();
    }

    @Override
    public void onCompleted(int requestType) {
        if(requestType == ATTENTION_GROUP_LIST_CODE)
            refreshLayout.refreshComplete();
        else if(requestType == ATTENTION_GROUP_CREATE)
            loading.cancel();
    }

    @Override
    public void onError(int requestType) {
//        if(requestType == ATTENTION_GROUP_CREATE)
//            ToasUtil.toast(this, "抱歉，新建分组失败，请稍后重试");
        onCompleted(requestType);
    }

    @Override
    public void onNext(IModel data, int requestType) {
        if(data.getErrcode() != 0){
            ToasUtil.toast(this, data.getMessage());
            onError(requestType);
        } else if(requestType == ATTENTION_GROUP_LIST_CODE){
            groupDatas.clear();
            List<AttentionGroupDetailModel> dataList = data.getList(AttentionGroupDetailModel.class);
            if(dataList != null && dataList.size() > 0)
                groupDatas.addAll(dataList);
            adapter.updateAdapter(groupDatas);
        } else if(requestType == ATTENTION_GROUP_CREATE){
            AttentionGroupDetailModel model = new AttentionGroupDetailModel();
            model.setId(data.getData().toString());
            model.setTitle((String) createGroupDialog.getTag());
            model.setConditionNum(0);
            model.setCountNum(0);
            model.setNewNum(0);
            groupDatas.add(model);
            adapter.updateAdapter(groupDatas);
        } else if(requestType%10 == ATTENTION_GROUP_DELETE){
        } else if(requestType%10 == ATTENTION_GROUP_RENAME){}
    }
}
